import {Component} from 'react';
import {connect} from 'react-redux';
import axios from 'axios';
import * as Notification from 'modules/notification/actions';
import Session from 'modules/auth/session';
import {Button, PageHeader} from 'antd';
import { Modal , Input,Table} from 'antd';
import styled from "styled-components";
import {func} from "prop-types";
import { Select } from 'antd';

const { Option } = Select;
const Outer = styled.div`
  border:1px solid #ececec;
  margin:20px;
  
   box-shadow: 3px 3px 6px rgba(0,0,0,0.1), 3px 3px 6px rgba(0,0,0,0.2);
`;

const Title = styled.div`
  background:#f1f1f1;
  height:50px;
  line-height:50px;
  text-indent:1em;
  color:#333;
  font-weight: bold;
`;

const Conten = styled.div`
  margin:20px;
  box-sizing:border-box;
`;

const Item = styled.div`
  display:flex;
  width:49%;
  margin:10px 0;
  float: left;
`;
const Bold = styled.span`
  font-weight:bold;
`;
const Clear = styled.span`
  clear:both;
      display: block;
    height: 0;
`;
const Inline = styled.span`
  display: inline-block;
    word-break: break-all;
    width: calc( 100% - 130px );
`;
const CenterBtn = styled.div`
  text-align:center;
  padding:80px 20px
`;

let constTime = 0;

class Collection extends Component {
    state = {
        search: '',
        document: {
            action: '',
            visible: false,
            dimmed: false
        },
        confirm: {
            visible: false,
            imsi: ''
        },
        view: {
            visible: false,
            disableOnClickOutside: false,
            imsi: ''
        },
        listData: [],
        visible: false,
        times:'30',
        waitTimes:30,
        showLoad:false,
        timeType:1,   //1未抓包  2.正在抓包  3.抓包结束
    };

    componentWillMount() {

        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/equipmentinfo',
            params: {},
            // data
        }).then(res => {
            $this.setState({
                    listData: res.data[0].listData
                }
            )

        })
    }

    getSData() {
        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/equipmentinfo',
            params: {},
            // data
        }).then(res => {
            this.setState({
                    listData: res.data[0].listData
                }
            )
            dispatch(Notification.success({
                title: '提示',
                message: `设备信息加载成功！`
            }));
        })
    }

    getByShell(times) {
        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }
        this.setState({
            waitTimes:times,
            showLoad:true
        });
         this.waitGetFile(times)
        var getIntrd=Date.parse(new Date())+times*1000
        this.setCookie('timeEnd',getIntrd,1)
        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/shellAction',
            params: {
                time:times
            },
            // data
        }).then(res => {
            const getData = res.data
           
        })
    }
    getFile(){
        const {dispatch} = this.props
        window.open('/static/file/Wireshark.pcap')
    }
    waitGetFile(times){
        var $this=this
        var getTime=times
        clearInterval(constTime)

        function waitT(){
            if(getTime <=0){
                clearInterval(constTime)
                $this.setState({
                    showLoad:false,
                    timeType:3
                });
            }else{
                getTime--
                $this.setState({
                    waitTimes:getTime
                });
            }
        }
        setTimeout(function () {
            constTime=setInterval(function () {
                waitT()
            },1000)
        },300)
    }

    getByStopShell(){
        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }
        clearInterval(constTime)
        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/shellActionStop',
            params: {},
            // data
        }).then(res => {
            const getData = res.data

            dispatch(Notification.info({
                title: '终止抓包结果',
                autoDismiss: 5,
                message: getData
            }));
            $this.setState({
                showLoad:false,
                timeType:3
            })
            document.cookie='timeEnd=1;expires='+new Date(0)
        })
    }
    showModal = () => {
        this.setState({
            visible: true,
            times:'30'
        });
    };

    handleOk = e => {
        var getTime=this.state.times
        this.setState({
            visible: false,
            timeType:2
        });
        let getTimes=isNaN(parseInt(getTime))?30:parseInt(getTime)
        if(getTimes<=0)getTimes=30
        this.getByShell(getTimes)
    };
    _handleChange(e) {
        let value = e.target.value;
        this.setState({
            times: value
        })
    };
    handleCancel = e => {
        console.log(e);
        this.setState({
            visible: false,
        });
    };

     setCookie(cname,cvalue,exdays)
    {
        var d = new Date();
        d.setTime(d.getTime()+(exdays*24*60*60*1000));
        var expires = "expires="+d.toGMTString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }


     getCookie(cname)
    {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++)
        {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) return c.substring(name.length,c.length);
        }
        return "";
    }

    setByCookies(){
        var getTT = this.getCookie('timeEnd')
        if(getTT != ''){
            var endParse=parseInt(getTT)
            var thisParse=Date.parse(new Date())
            if(endParse>thisParse){
                //倒计时
                var getTime=parseInt((endParse-thisParse)/1000)
                this.setState({
                    timeType:2,
                    times:getTime
                })
                this.waitGetFile(getTime)
            }else{
                //结束
                this.setState({
                    timeType:3
                })
                document.cookie='timeEnd=1;expires='+new Date(0)
            }
        }

    }

    componentDidMount(){
         this.setByCookies()
    }

    componentWillUnmount() {
        clearInterval(constTime)
    }

    render() {
        let $this = this
        const textArra = ['未启动', '运行正常']
        const textArraMore = ['断开', '建链成功']
        // const Equipment_infoList = this.state.listData.map((ic, index) =>
        //     <Item key={index}><Bold>{ic.name == 'NG'?'NG接口':ic.name}：</Bold> <Inline>{index >= 12 ? (ic.name == 'NG'?(textArraMore[ic.value]):(textArra[ic.value])) : ic.value} </Inline>
        //     </Item>
        // );

        function handleChange(value) {
            $this.setState({
                times: value
            })
        }





        const columns = [

            {
                title: '网口选择',
                key: 'netSelect',
                dataIndex: 'tags',
                render: tags => (
                    <Select defaultValue="any" style={{ width: 120 }} onChange={handleChange}>
                        <Option value="any">any</Option>
                    </Select>
                ),
            },
            {
                title: '协议选择',
                key: 'netXy',
                dataIndex: 'tags',
                render: tags => (
                    <Select defaultValue="any" style={{ width: 120 }} onChange={handleChange}>
                        <Option value="any">any</Option>
                    </Select>
                ),
            },
            {
                title: '端口号',
                key: 'netport',
                dataIndex: 'tags',
                render: tags => (
                    <Select defaultValue="any" style={{ width: 120 }} onChange={handleChange}>
                        <Option value="any">any</Option>
                    </Select>
                ),
            },
            {
                title: '抓包时间',
                key: 'netTime',
                dataIndex: 'tags',
                render: tags => (
                    <Select defaultValue="30" style={{ width: 120 }} onChange={handleChange}>
                        <Option value="5">5</Option>
                        <Option value="10">10</Option>
                        <Option value="30">30</Option>
                        <Option value="50">50</Option>
                        <Option value="100">100</Option>
                        <Option value="150">150</Option>
                    </Select>
                ),
            },
        ];

        const data = [
            {
                key: '1',
                name: 'John Brown',
                age: 32,
                address: 'New York No. 1 Lake Park',
                tags: ['nice', 'developer'],
            },
        ];



        return (
            <div>
                <PageHeader
                    style={{
                        border: '1px solid rgb(235, 237, 240)',
                    }}
                    title="一键抓包"
                />
                {/*<Outer>*/}
                {/*    <Conten>*/}
                {/*        {Equipment_infoList}*/}
                {/*        <Clear></Clear>*/}
                {/*    </Conten>*/}
                {/*</Outer>*/}
                <div className="noFooterBox" style={{margin:20,padding:10,boxShadow: '3px 3px 6px rgba(0,0,0,0.1), 3px 3px 6px rgba(0,0,0,0.2)',border: '1px solid #ececec'}}>
                    <Table columns={columns} dataSource={data}> </Table>
                </div>



                <div style={{display:(this.state.timeType == 1 ?'block':'none')}}>
                    <CenterBtn >
                        {/*<Button type="primary" onClick={() => this.getSData()}>刷新</Button>*/}
                        {/*<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>*/}
                        <Button type="primary" ghost onClick={() => this.handleOk()}>一键抓包</Button>
                    </CenterBtn>
                </div>


                <div style={{display:(this.state.timeType == 2 ?'block':'none')}}>
                    <CenterBtn >
                        {/*<Button type="primary" onClick={() => this.getSData()}>刷新</Button>*/}
                        {/*<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>*/}
                        <Button type="primary" ghost  disabled={true}>一键抓包</Button>
                        <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                        <Button type="primary" ghost onClick={() => this.getByStopShell()}>停止抓包</Button>
                    </CenterBtn>
                    <div>
                        <p style={{textAlign:'center'}}>正在抓包中，剩余{this.state.waitTimes}秒</p>
                    </div>
                </div>

               <div  style={{display:(this.state.timeType == 3 ?'block':'none')}}>
                   <CenterBtn>
                       {/*<Button type="primary" onClick={() => this.getSData()}>刷新</Button>*/}
                       {/*<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>*/}
                       <Button type="primary" ghost onClick={() => this.handleOk()}>一键抓包</Button>
                       <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                       <Button type="primary" ghost onClick={() => this.getFile()}>下载</Button>
                   </CenterBtn>
               </div>




            </div>
        )
    }
}

Collection = connect(
    (state) => ({})
)(Collection);

export default Collection;